package com.chen.controller.user;

import com.chen.common.constant.MessageConstant;
import com.chen.common.result.Result;
import com.chen.common.utils.JwtUtil;
import com.chen.common.utils.Md5Util;
import com.chen.popj.dto.UserChangesPassWordDTO;
import com.chen.popj.dto.UserDTO;
import com.chen.popj.entity.User;
import com.chen.popj.vo.ProblemSubmitVO;
import com.chen.popj.vo.UserVO;
import com.chen.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    HttpServletRequest httpServletRequest;

    /**
     * 用户注册
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result<Object> register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        System.out.println(username);
        System.out.println(password);

        // 判断用户名和密码是否存在
        if (username.isEmpty() || password.isEmpty()) {
            return Result.error(MessageConstant.INPUT_USERNAME_PASSWORD);
        }

        // 查询用户名是否重复
        User user = userService.queryByUsername(username);
        if (user != null) {
            return Result.error(MessageConstant.ALREADY_EXISTS);
        }
        user = User.builder()
                .username(username)
                .password(password)
                .build();
        BeanUtils.copyProperties(userDTO, user);
        // 注册用户
        userService.register(user);
        return Result.success();
    }

    /**
     * 用户登录
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (username.isEmpty() || password.isEmpty()) {
            return Result.error(MessageConstant.INPUT_USERNAME_PASSWORD);
        }
        User user = userService.queryByUsername(username);
        if (user == null) {
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (Md5Util.getMD5String(userDTO.getPassword()).equals(user.getPassword())) {
            HashMap<String, Object> claim = new HashMap<>();
            claim.put("id", user.getId());
            claim.put("username", user.getUsername());
            claim.put("role", user.getRole());
            String token = JwtUtil.genToken(claim);
            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
            opsForValue.set(token, token, 12, TimeUnit.HOURS);
            if (user.getRole() == 1) {
                return Result.success(token, 2);
            }
            log.info("token:{}", token);
            return Result.success(token);
        }
        return Result.success(MessageConstant.PASSWORD_ERROR);
    }

    /**
     * 用户退出登录
     *
     * @return
     */
    @PostMapping("/quit")
    public Result<Object> quit() {
        userService.quit();
        log.info("退出登录成功");
        return Result.success();
    }

    /**
     * 获取用户id
     *
     * @return
     */
    @GetMapping("/getUserId")
    public Result<Integer> getUserId() {
        String authorization = httpServletRequest.getHeader("Authorization");
        Map<String, Object> parseToken = JwtUtil.parseToken(authorization);
        Integer userId = (Integer) parseToken.get("id");
        return Result.success(userId);
    }

    /**
     * 获取用户名
     *
     * @return
     */
    @GetMapping("/getUserNameAndAvatar")
    public Result<UserVO> getUserNameAndAvatar() {
        UserVO userVO = userService.getUserNameAndAvatar();
        return Result.success(userVO);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result<UserVO> getUserInfo() {
//        System.out.println("getUserInfo");
        return Result.success(userService.getUserInfo());
    }

    /**
     * 根据用户id修改用户基本资料
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/userInfoUpdate")
    public Result<Object> userInfoUpdate(@RequestBody UserDTO userDTO) {
        userService.userInfoUpdate(userDTO);
        return Result.success();
    }

    /**
     * 根据用户id修改用户密码
     *
     * @param userChangesPassWordDTO
     * @return
     */
    @PostMapping("/userPasswordUpdate")
    public Result<Object> userPasswordUpdate(@RequestBody UserChangesPassWordDTO userChangesPassWordDTO) {
        userService.userPasswordUpdate(userChangesPassWordDTO);
        return Result.success();
    }

    /**
     * 根据用户id获取用户个人做题记录
     *
     * @return
     */
    @GetMapping("/submitRecord")
    public Result<ArrayList<ProblemSubmitVO>> getSubmitRecord() {
        return Result.success(userService.getSubmitRecord());
    }

    /**
     * 上传头像
     *
     * @param avatarUrl
     * @return
     */
    @PostMapping("/uploadAvatar")
    public Result<String> upload(@RequestParam @URL String avatarUrl) {
        userService.uploadAvatar(avatarUrl);
        return Result.success();
    }
}
